package cn.ug.analyse.service.impl;

import cn.ug.analyse.bean.ChannelMemberBean;
import cn.ug.analyse.bean.request.*;
import cn.ug.analyse.bean.response.*;
import cn.ug.analyse.bean.status.CommonConstants;
import cn.ug.analyse.mapper.MemberAnalyseMapper;
import cn.ug.analyse.mapper.entity.MemberAnalyse;
import cn.ug.analyse.service.MemberAnalyseService;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.ensure.Ensure;
import cn.ug.feign.BillService;
import cn.ug.pay.bean.request.FinanceBillParam;
import cn.ug.pay.bean.response.ActiveMemberBean;
import cn.ug.pay.bean.response.ActiveTotalBean;
import cn.ug.util.Common;
import cn.ug.util.UF;
import cn.ug.util.Week;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import static cn.ug.util.ConstantUtil.NORMAL_MONTH_FORMAT;

@Service
public class MemberAnalyseServiceImpl implements MemberAnalyseService {

    @Resource
    private MemberAnalyseMapper memberAnalyseMapper;

    @Resource
    private BillService billService;

    @Resource
    private DozerBeanMapper dozerBeanMapper;

    private static Logger logger = LoggerFactory.getLogger(MemberAnalyseServiceImpl.class);

    @Override
    public void addMemberAnalyse(MemberAnalyseMsgParamBean entity) {
        MemberAnalyse memberAnalyse = dozerBeanMapper.map(entity, MemberAnalyse.class);
        memberAnalyse.setId(UF.getRandomUUID());
        if (entity.getType() == 3 || entity.getType() == 4) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("memberId", entity.getMemberId());
            param.put("type", entity.getType());
            Integer count = memberAnalyseMapper.findMemberAnalyseCount(param);
            if (count == 0) {
                memberAnalyseMapper.insert(memberAnalyse);
            }
        } else {
            memberAnalyseMapper.insert(memberAnalyse);
        }
    }

    @Override
    public MemberAnalyseBean getChannelDetail(String channelId) {
        if (StringUtils.isBlank(channelId)) {
            return null;
        }
        List<String> channels = new ArrayList<String>();
        channels.add(channelId);
        List<MemberAnalyseBean> data = memberAnalyseMapper.findList(channels, "", "");
        if (data != null && data.size() > 0) {
            return data.get(0);
        }
        return null;
    }

    @Override
    public List<MemberAnalyseBean> findList(MemberAnalyseParamBean entity) {
        List<String> channels = null;
        if (entity.getChannelIds() != null && entity.getChannelIds().length > 0) {
            channels = new ArrayList<String>();
            for (String channelId : entity.getChannelIds()) {
                channels.add(channelId);
            }
        }
        return memberAnalyseMapper.findList(channels, entity.getStartTime(), entity.getEndTime());
    }

    @Override
    public DataTable<ActiveMemberBean> findBuySellActiveMemberList(FinanceBillParam financeBillParam) {
        String channelId = "";
        if (financeBillParam.getChannelIds() != null && financeBillParam.getChannelIds().length > 0) {
            for (String str : financeBillParam.getChannelIds()) {
                channelId += str + ",";
            }
            if (StringUtils.isNotBlank(channelId)) {
                channelId = StringUtils.substring(channelId, 0, StringUtils.length(channelId) - 1);
            }
        }
        SerializeObject<List<ActiveMemberBean>> o = billService.findBuySellActiveMemberList(financeBillParam.getStartTime(), financeBillParam.getEndTime(), channelId);
        if (o.getCode() == ResultType.NORMAL) {
            List<ActiveMemberBean> list = o.getData();
            if (list != null && !list.isEmpty()) {

                //月汇总
                if (financeBillParam.getDayType() == 2) {
                    list = getActiveMemberList(list);
                } else if (financeBillParam.getDayType() == 1) {
                    Collections.reverse(list);
                } else if (financeBillParam.getDayType() == 3) {
                    list = findEvenyWeek(list);
                }
                int total = list.size();
                //数据分页
                //计算  
                int num = (financeBillParam.getPageNum() - 1) * financeBillParam.getPageSize();
                list = list.stream().skip(num).collect(Collectors.toList());
                List<ActiveMemberBean> pageList = list.stream().limit(financeBillParam.getPageSize()).collect(Collectors.toList());
                return new DataTable<>(financeBillParam.getPageNum(), financeBillParam.getPageSize(), total, pageList);
            } else {
                return new DataTable<>(financeBillParam.getPageNum(), financeBillParam.getPageSize(), 0, new ArrayList<>());
            }
        }
        return null;
    }

    @Override
    public List<ActiveMemberBean> findBuySellActiveMemberWeekList(FinanceBillParam financeBillParam) {
        String channelId = "";
        if (financeBillParam.getChannelIds() != null && financeBillParam.getChannelIds().length > 0) {
            for (String str : financeBillParam.getChannelIds()) {
                channelId += str + ",";
            }
            if (StringUtils.isNotBlank(channelId)) {
                channelId = StringUtils.substring(channelId, 0, StringUtils.length(channelId) - 1);
            }
        }
        SerializeObject<List<ActiveMemberBean>> o = billService.findBuySellActiveMemberList(financeBillParam.getStartTime(), financeBillParam.getEndTime(), channelId);
        if (o.getCode() == ResultType.NORMAL) {
            List<ActiveMemberBean> list = o.getData();
            if (list != null && !list.isEmpty()) {
                //月汇总
                if (financeBillParam.getDayType() == 3) {
                    list = getActiveMemberList(list);
                } else if (financeBillParam.getDayType() == 2) {
                    list = findEvenyWeek(list);
                }
            }
            return list;
        }
        return null;
    }

    @Override
    public List<ActiveTotalBean> findBuySellActiveMemberTotal(FinanceBillParam financeBillParam) {
        List<ActiveTotalBean> resultList = new ArrayList<ActiveTotalBean>();
        String channelId = "";
        if (financeBillParam.getChannelIds() != null && financeBillParam.getChannelIds().length > 0) {
            for (String str : financeBillParam.getChannelIds()) {
                channelId += str + ",";
            }
            if (StringUtils.isNotBlank(channelId)) {
                channelId = StringUtils.substring(channelId, 0, StringUtils.length(channelId) - 1);
            }
        }
        SerializeObject<List<ActiveMemberBean>> o = billService.findBuySellActiveMemberList(financeBillParam.getStartTime(), financeBillParam.getEndTime(), channelId);
        if (o.getCode() == ResultType.NORMAL) {
            List<ActiveMemberBean> list = o.getData();
            Integer buyNumber = 0;
            Integer sellerNumber = 0;
            if (list != null && !list.isEmpty()) {
                for (ActiveMemberBean entity : list) {
                    buyNumber += entity.getBuyNumber();
                    sellerNumber += entity.getSellerNumber();
                }
            }
            ActiveTotalBean totalBean = new ActiveTotalBean();
            totalBean.setType(1);
            totalBean.setNumber(buyNumber);

            ActiveTotalBean totalBean1 = new ActiveTotalBean();
            totalBean1.setType(2);
            totalBean1.setNumber(sellerNumber);
            resultList.add(totalBean);
            resultList.add(totalBean1);
        }
        return resultList;
    }

    /**
     * 按周统计
     *
     * @param list
     * @return
     */
    public List<ActiveMemberBean> findEvenyWeek(List<ActiveMemberBean> list) {
        List<ActiveMemberBean> resultList = new ArrayList<ActiveMemberBean>();

        //根据起始时间和结束时间获取周
        LocalDate startTime = LocalDate.parse(list.get(0).getDay(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endTime = LocalDate.parse(list.get(list.size() - 1).getDay(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<Week> weekList = Common.getWeekList(startTime, endTime);


        for (Week week : weekList) {
            ActiveMemberBean activeMemberBean = new ActiveMemberBean();
            activeMemberBean.setDay(week.getDay());
            BigDecimal amount = BigDecimal.ZERO;
            Integer buyNumber = 0;
            Integer sellerNumber = 0;
            if (list != null && !list.isEmpty()) {
                List<ActiveMemberBean> filterList = list.stream().filter(o -> o.getDayNumber() >= week.getStartTimeNumber() && o.getDayNumber() <= week.getEndTimeNumber()).collect(Collectors.toList());
                if (filterList != null && !filterList.isEmpty()) {
                    for (ActiveMemberBean entity : filterList) {
                        buyNumber += entity.getBuyNumber();
                        sellerNumber += entity.getSellerNumber();
                    }
                }
            }
            activeMemberBean.setBuyNumber(buyNumber);
            activeMemberBean.setSellerNumber(sellerNumber);
            resultList.add(activeMemberBean);
        }
        return resultList;
    }

    @Override
    public Map<String, Object> findDormancyMember(DormancyMemberParamBean paramBean) {
        logger.info("--------会员休眠用户-----开始");
        Map<String, Object> result = new HashMap<String, Object>();
        if (paramBean.getBindingBankCardDay() != null && paramBean.getBindingBankCardDay() != 0) {
            result.put("noBindingBankCard", memberAnalyseMapper.findNoBindingBankCardTotal(paramBean));
            logger.info("-------绑卡查询---");
        } else {
            result.put("noBindingBankCard", 0);
        }
        if (paramBean.getTradeDay() != null && paramBean.getTradeDay() != 0) {
            result.put("noTrade", memberAnalyseMapper.findNoTradeTotal(paramBean));
            logger.info("-------交易查询---");
        } else {
            result.put("noTrade", 0);
        }
        logger.info("--------会员休眠用户-----结束");
        return result;
    }

    @Override
    public List<MemberProtrayBean> findMemberProtrayList(MemberPortrayParamBean paramBean) {
        List<MemberProtrayBean> resultList = new ArrayList<MemberProtrayBean>();
        MemberProtrayBean dt1 = new MemberProtrayBean();
        MemberProtrayBean dt2 = new MemberProtrayBean();

        //设置常量
        Ensure.that(paramBean.getType()).isNull("");
        if (paramBean.getType() == 1) {
            paramBean.setKeywords(CommonConstants.MemberPortrayType.GENDER);
        } else if (paramBean.getType() == 2) {
            paramBean.setKeywords(CommonConstants.MemberPortrayType.AGE);
        } else if (paramBean.getType() == 3) {
            paramBean.setKeywords(CommonConstants.MemberPortrayType.SOURCE);
        }

        if (paramBean.getUserType() != null && paramBean.getUserType() == 2 && paramBean.getTraderTypeHz() != null && paramBean.getTraderTypeHz() == 1) {
            List<String> memberIds = memberAnalyseMapper.queryMemberUserByLeasebackDay(paramBean.getLeasebackDay(), paramBean.getCharacter());
            if (!CollectionUtils.isEmpty(memberIds)){
                paramBean.setMemberIds(memberIds);
            }else {
                return resultList;
            }
        }
        List<MemberProtrayBean> beas = new ArrayList<>();
        if(paramBean.getType()==4){
            //todo 交易时间段分布
        }
        if (paramBean.getType()==5){
            paramBean.setKeywords(CommonConstants.MemberPortrayType.GENDER);
            //邀请比例
            List<MemberFriendBean> friendBeanList = memberAnalyseMapper.queryFriendList(paramBean);
            if (paramBean.getInviteType()==1){
                //主动参与用户集合
                List<MemberFriendBean> list1 = friendBeanList.stream().filter(o -> o.getFriendId() == null).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(list1)){
                    List<String> memberIdList = list1.stream().map(o->o.getMemberId()).collect(Collectors.toList());
                    paramBean.setMemberIds(memberIdList);
                }else {
                    return resultList;
                }

            }else if (paramBean.getInviteType()==2){
                List<MemberFriendBean> list1 = friendBeanList.stream().filter(o -> o.getFriendId() != null).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(list1)){
                    List<String> memberIdList = list1.stream().map(o->o.getMemberId()).collect(Collectors.toList());
                    paramBean.setMemberIds(memberIdList);
                }else {
                    return resultList;
                }
            }
            beas = memberAnalyseMapper.queryForMemberGram(paramBean);
        } else{
            beas = memberAnalyseMapper.queryForMemberGram(paramBean);
        }


        if (!CollectionUtils.isEmpty(beas)) {
            if (paramBean.getUserType() != null) {
                //数据转换  对外统一提供固定的字段
                if (paramBean.getUserType() == 2) {
                    for (MemberProtrayBean memberProtrayBean : beas) {
                        memberProtrayBean.setAverageBuyAmount(memberProtrayBean.getHzAverageBuyAmount());
                        memberProtrayBean.setTraderNum(memberProtrayBean.getHzTraderNum());
                        memberProtrayBean.setHzAverageBuyAmount(null);
                        memberProtrayBean.setHzTraderNum(null);
                    }
                }

                if (paramBean.getUserType() == 3) {
                    for (MemberProtrayBean memberProtrayBean : beas) {
                        memberProtrayBean.setAverageBuyAmount(memberProtrayBean.getMjAverageBuyAmount());
                        memberProtrayBean.setTraderNum(memberProtrayBean.getMjTraderNum());
                        memberProtrayBean.setMjAverageBuyAmount(null);
                        memberProtrayBean.setMjTraderNum(null);
                    }
                }
            } else {
                for (MemberProtrayBean memberProtrayBean : beas) {
                    memberProtrayBean.setHzAverageBuyAmount(null);
                    memberProtrayBean.setHzTraderNum(null);
                    memberProtrayBean.setMjAverageBuyAmount(null);
                    memberProtrayBean.setMjTraderNum(null);
                }
            }
        }

        if (paramBean.getType() == 1) {
            for (MemberProtrayBean protrayBean : beas) {
                if (protrayBean.getGender() == 1) {
                    dt1 = protrayBean;
                }
                if (protrayBean.getGender() == 2) {
                    dt2 = protrayBean;
                }
            }
            if (dt1.getNumber() == null) {
                dt1.setNumber(BigDecimal.ZERO);
            }
            if (dt2.getNumber() == null) {
                dt2.setNumber(BigDecimal.ZERO);
            }
            if (BigDecimal.ZERO.compareTo(dt1.getNumber()) == 0 || BigDecimal.ZERO.compareTo(dt2.getNumber()) == 0) {
                dt1.setPer(BigDecimal.ZERO);
                dt2.setPer(BigDecimal.ZERO);
            } else {
                BigDecimal total = dt1.getNumber().add(dt2.getNumber());
                BigDecimal per1 = dt1.getNumber().divide(total, 4, BigDecimal.ROUND_HALF_UP);
                BigDecimal per2 = dt2.getNumber().divide(total, 4, BigDecimal.ROUND_HALF_UP);
                dt1.setPer(per1);
                dt2.setPer(per2);
            }
            resultList.add(dt1);
            resultList.add(dt2);
        } else if (paramBean.getType() == 2) {
            if (beas != null && beas.size() > 0) {
                dt1 = beas.get(0);
                if (dt1.getNumber() == null) {
                    dt1.setNumber(BigDecimal.ZERO);
                }
                if (dt1.getAccountAmount() == null) {
                    dt1.setAccountAmount(BigDecimal.ZERO);
                }
                if (dt1.getGramTotal() == null) {
                    dt1.setGramTotal(BigDecimal.ZERO);
                }
                if (dt1.getAverageBuyAmount() == null) {
                    dt1.setAverageBuyAmount(BigDecimal.ZERO);
                }
                if (dt1.getAverageRegularGram() == null) {
                    dt1.setAverageRegularGram(BigDecimal.ZERO);
                }
                if (dt1.getAverageCurrentGram() == null) {
                    dt1.setAverageCurrentGram(BigDecimal.ZERO);
                }
            } else {
                dt1.setNumber(BigDecimal.ZERO);
                dt1.setAccountAmount(BigDecimal.ZERO);
                dt1.setGramTotal(BigDecimal.ZERO);
                dt1.setAverageBuyAmount(BigDecimal.ZERO);
                dt1.setAverageCurrentGram(BigDecimal.ZERO);
                dt1.setAverageRegularGram(BigDecimal.ZERO);
                dt1.setPer(BigDecimal.ZERO);
            }
            int totalNum = memberAnalyseMapper.getMemberNum(paramBean);
            if (totalNum == 0 && BigDecimal.ZERO.compareTo(dt1.getNumber()) == 0) {
                dt1.setPer(BigDecimal.ZERO);
            } else {
                BigDecimal per1 = dt1.getNumber().divide(new BigDecimal(totalNum), 4, BigDecimal.ROUND_HALF_UP);
                dt1.setPer(per1.multiply(BigDecimal.valueOf(100L)));
            }
            resultList.add(dt1);
        } else if (paramBean.getType() == 3) {
            for (MemberProtrayBean protrayBean : beas) {
                if (protrayBean.getSource() == 2) {
                    dt1 = protrayBean;
                }
                if (protrayBean.getSource() == 3) {
                    dt2 = protrayBean;
                }
            }
            if (dt1.getNumber() == null) {
                dt1.setNumber(BigDecimal.ZERO);
            }
            if (dt2.getNumber() == null) {
                dt2.setNumber(BigDecimal.ZERO);
            }
            if (BigDecimal.ZERO.compareTo(dt1.getNumber()) == 0 || BigDecimal.ZERO.compareTo(dt2.getNumber()) == 0) {
                dt1.setPer(BigDecimal.ZERO);
                dt2.setPer(BigDecimal.ZERO);
            } else {
                BigDecimal total = dt1.getNumber().add(dt2.getNumber());
                BigDecimal per1 = dt1.getNumber().divide(total, 4, BigDecimal.ROUND_HALF_UP);
                BigDecimal per2 = dt2.getNumber().divide(total, 4, BigDecimal.ROUND_HALF_UP);
                dt1.setPer(per1);
                dt2.setPer(per2);
            }
            resultList.add(dt1);
            resultList.add(dt2);
        }
        if (paramBean.getType() == 5) {
            for (MemberProtrayBean protrayBean : beas) {
                if (protrayBean.getGender() == 1) {
                    dt1 = protrayBean;
                }
                if (protrayBean.getGender() == 2) {
                    dt2 = protrayBean;
                }
            }
            if (dt1.getNumber() == null) {
                dt1.setNumber(BigDecimal.ZERO);
            }
            if (dt2.getNumber() == null) {
                dt2.setNumber(BigDecimal.ZERO);
            }
            if (BigDecimal.ZERO.compareTo(dt1.getNumber()) == 0 && BigDecimal.ZERO.compareTo(dt2.getNumber()) == 0) {
                dt1.setPer(BigDecimal.ZERO);
                dt2.setPer(BigDecimal.ZERO);
            }if (BigDecimal.ZERO.compareTo(dt1.getNumber()) == 0 && BigDecimal.ZERO.compareTo(dt2.getNumber()) < 0) {
                dt1.setPer(BigDecimal.ZERO);
                dt2.setPer(new BigDecimal(1));
            }if (BigDecimal.ZERO.compareTo(dt1.getNumber()) < 0 && BigDecimal.ZERO.compareTo(dt2.getNumber()) == 0) {
                dt1.setPer(new BigDecimal(1));
                dt2.setPer(BigDecimal.ZERO);
            }   else {
                BigDecimal total = dt1.getNumber().add(dt2.getNumber());
                BigDecimal per1 = dt1.getNumber().divide(total, 4, BigDecimal.ROUND_HALF_UP);
                BigDecimal per2 = dt2.getNumber().divide(total, 4, BigDecimal.ROUND_HALF_UP);
                dt1.setPer(per1);
                dt2.setPer(per2);
            }
            resultList.add(dt1);
            resultList.add(dt2);
        }

        return resultList;
    }

    @Override
    public List<MemberProtrayBean> findAgeProtrayList() {

        return null;
    }

    @Override
    public List<MemberRatioBean> findMemberAgeList(MemberAngParamBean memberAngParamBean) {
        List<MemberRatioBean> result = new ArrayList<MemberRatioBean>();
        //回租用户 并且有回租时长查询条件
        if (memberAngParamBean.getUserType() != null && memberAngParamBean.getUserType() == 2 && memberAngParamBean.getTraderTypeHz() != null && memberAngParamBean.getTraderTypeHz() == 1) {
            List<String> memberIds = memberAnalyseMapper.queryMemberUserByLeasebackDay(memberAngParamBean.getLeasebackDay(), memberAngParamBean.getCharacter());
            if (!CollectionUtils.isEmpty(memberIds)){
                memberAngParamBean.setMemberIds(memberIds);
            }else {
                 return result;
            }
        }

        List<MemberAngBean> ageList = memberAnalyseMapper.findMemberAgeList(memberAngParamBean);
        if (ageList != null) {
            //18岁一下
            List<MemberAngBean> list1 = ageList.stream().filter(o -> o.getAge().compareTo(BigDecimal.valueOf(0)) > 0 && o.getAge().compareTo(BigDecimal.valueOf(18)) < 0).collect(Collectors.toList());
            DecimalFormat df = new DecimalFormat("0.0000");
            MemberRatioBean memberRatioBean1 = new MemberRatioBean();
            if (list1 != null && !list1.isEmpty()) {
                //分别统计18岁一下男女人数
                Long maxs = list1.stream().filter(o -> o.getGender() == 1).count();
                int womans = list1.size() - maxs.intValue();
                memberRatioBean1.setMaxRatio(df.format((float) maxs.intValue() / ageList.size()));
                memberRatioBean1.setWomanRatio(df.format((float) womans / ageList.size()));
                result.add(memberRatioBean1);
                //result.add(df.format((float)list1.size()/ageList.size()));
            } else {
                memberRatioBean1.setMaxRatio(BigDecimal.ZERO.toString());
                memberRatioBean1.setWomanRatio(BigDecimal.ZERO.toString());
                result.add(memberRatioBean1);
            }
            //18岁到24岁
            List<MemberAngBean> list2 = ageList.stream().filter(o -> o.getAge().compareTo(BigDecimal.valueOf(18)) >= 0 && o.getAge().compareTo(BigDecimal.valueOf(24)) <= 0).collect(Collectors.toList());
            MemberRatioBean memberRatioBean2 = new MemberRatioBean();
            if (list2 != null && !list2.isEmpty()) {
                //分别统计18岁到24岁一下男女人数
                Long maxs = list2.stream().filter(o -> o.getGender() == 1).count();
                int womans = list2.size() - maxs.intValue();
                memberRatioBean2.setMaxRatio(df.format((float) maxs.intValue() / ageList.size()));
                memberRatioBean2.setWomanRatio(df.format((float) womans / ageList.size()));
                result.add(memberRatioBean2);
            } else {
                memberRatioBean2.setMaxRatio(BigDecimal.ZERO.toString());
                memberRatioBean2.setWomanRatio(BigDecimal.ZERO.toString());
                result.add(memberRatioBean2);
            }
            //25岁到34岁
            List<MemberAngBean> list3 = ageList.stream().filter(o -> o.getAge().compareTo(BigDecimal.valueOf(25)) >= 0 && o.getAge().compareTo(BigDecimal.valueOf(34)) <= 0).collect(Collectors.toList());
            MemberRatioBean memberRatioBean3 = new MemberRatioBean();
            if (list3 != null && !list3.isEmpty()) {
                //分别统计25岁到34岁一下男女人数
                Long maxs = list3.stream().filter(o -> o.getGender() == 1).count();
                int womans = list3.size() - maxs.intValue();
                memberRatioBean3.setMaxRatio(df.format((float) maxs.intValue() / ageList.size()));
                memberRatioBean3.setWomanRatio(df.format((float) womans / ageList.size()));
                result.add(memberRatioBean3);
            } else {
                memberRatioBean3.setMaxRatio(BigDecimal.ZERO.toString());
                memberRatioBean3.setWomanRatio(BigDecimal.ZERO.toString());
                result.add(memberRatioBean3);
            }
            //35岁到44岁
            List<MemberAngBean> list4 = ageList.stream().filter(o -> o.getAge().compareTo(BigDecimal.valueOf(35)) >= 0 && o.getAge().compareTo(BigDecimal.valueOf(44)) <= 0).collect(Collectors.toList());
            MemberRatioBean memberRatioBean4 = new MemberRatioBean();
            if (list4 != null && !list4.isEmpty()) {
                //分别统计35岁到44岁一下男女人数
                Long maxs = list4.stream().filter(o -> o.getGender() == 1).count();
                int womans = list4.size() - maxs.intValue();
                memberRatioBean4.setMaxRatio(df.format((float) maxs.intValue() / ageList.size()));
                memberRatioBean4.setWomanRatio(df.format((float) womans / ageList.size()));
                result.add(memberRatioBean4);
            } else {
                memberRatioBean4.setMaxRatio(BigDecimal.ZERO.toString());
                memberRatioBean4.setWomanRatio(BigDecimal.ZERO.toString());
                result.add(memberRatioBean4);
            }
            //44岁到54岁
            List<MemberAngBean> list5 = ageList.stream().filter(o -> o.getAge().compareTo(BigDecimal.valueOf(44)) >= 0 && o.getAge().compareTo(BigDecimal.valueOf(54)) <= 0).collect(Collectors.toList());
            MemberRatioBean memberRatioBean5 = new MemberRatioBean();
            if (list5 != null && !list5.isEmpty()) {
                //分别统计44岁到54岁一下男女人数
                Long maxs = list5.stream().filter(o -> o.getGender() == 1).count();
                int womans = list5.size() - maxs.intValue();
                memberRatioBean5.setMaxRatio(df.format((float) maxs.intValue() / ageList.size()));
                memberRatioBean5.setWomanRatio(df.format((float) womans / ageList.size()));
                result.add(memberRatioBean5);
            } else {
                memberRatioBean5.setMaxRatio(BigDecimal.ZERO.toString());
                memberRatioBean5.setWomanRatio(BigDecimal.ZERO.toString());
                result.add(memberRatioBean5);
            }
            //55岁到64岁
            List<MemberAngBean> list6 = ageList.stream().filter(o -> o.getAge().compareTo(BigDecimal.valueOf(55)) >= 0 && o.getAge().compareTo(BigDecimal.valueOf(64)) <= 0).collect(Collectors.toList());
            MemberRatioBean memberRatioBean6 = new MemberRatioBean();
            if (list6 != null && !list6.isEmpty()) {
                //分别统计55岁到64岁一下男女人数
                Long maxs = list6.stream().filter(o -> o.getGender() == 1).count();
                int womans = list6.size() - maxs.intValue();
                memberRatioBean6.setMaxRatio(df.format((float) maxs.intValue() / ageList.size()));
                memberRatioBean6.setWomanRatio(df.format((float) womans / ageList.size()));
                result.add(memberRatioBean6);
            } else {
                memberRatioBean6.setMaxRatio(BigDecimal.ZERO.toString());
                memberRatioBean6.setWomanRatio(BigDecimal.ZERO.toString());
                result.add(memberRatioBean6);
            }
            //64岁以上
            List<MemberAngBean> list7 = ageList.stream().filter(o -> o.getAge().compareTo(BigDecimal.valueOf(65)) >= 0).collect(Collectors.toList());
            MemberRatioBean memberRatioBean7 = new MemberRatioBean();
            if (list7 != null && !list7.isEmpty()) {
                //分别统计64岁以上一下男女人数
                Long maxs = list7.stream().filter(o -> o.getGender() == 1).count();
                int womans = list7.size() - maxs.intValue();
                memberRatioBean7.setMaxRatio(df.format((float) maxs.intValue() / ageList.size()));
                memberRatioBean7.setWomanRatio(df.format((float) womans / ageList.size()));
                result.add(memberRatioBean7);
            } else {
                memberRatioBean7.setMaxRatio(BigDecimal.ZERO.toString());
                memberRatioBean7.setWomanRatio(BigDecimal.ZERO.toString());
                result.add(memberRatioBean7);
            }
        }
        return result;
    }

    @Override
    public List<Integer> findTerminalMember() {
        List<Integer> list = new ArrayList<Integer>();
        //查询终端为安卓用户
        list.add(memberAnalyseMapper.findTerminalMember(2));
        //查询终端为苹果用户
        list.add(memberAnalyseMapper.findTerminalMember(3));
        return list;
    }

    @Override
    public Integer findRegisterMember(String channelId) {
        return memberAnalyseMapper.findRegisterMember(channelId);
    }

    @Override
    public List<ChannelMemberBean> queryForList(String channelId, int offset, int size) {
        if (StringUtils.isNotBlank(channelId)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("channelId", channelId);
            params.put("offset", offset);
            params.put("size", size);
            return memberAnalyseMapper.queryForList(params);
        }
        return null;
    }

    @Override
    public int queryForCount(String channelId) {
        if (StringUtils.isNotBlank(channelId)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("channelId", channelId);
            return memberAnalyseMapper.queryForCount(params);
        }
        return 0;
    }


    @Override
    public List<MemberRatioBean> findMemberFriendList(MemberAngParamBean memberAngParamBean) {
        List<MemberRatioBean> resultList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.0000");
        //回租用户 并且有回租时长查询条件
        if (memberAngParamBean.getUserType() != null && memberAngParamBean.getUserType() == 2 &&
                memberAngParamBean.getTraderTypeHz() != null && memberAngParamBean.getTraderTypeHz() == 1) {
            List<String> memberIds = memberAnalyseMapper.queryMemberUserByLeasebackDay(memberAngParamBean.getLeasebackDay(), memberAngParamBean.getCharacter());
            if (!CollectionUtils.isEmpty(memberIds)){
                memberAngParamBean.setMemberIds(memberIds);
            }else {
                return resultList;
            }
        }
        List<MemberFriendBean> friendBeanList = memberAnalyseMapper.queryFriendList(memberAngParamBean);
        if (!CollectionUtils.isEmpty(friendBeanList)) {
            //主动参与用户集合
            List<MemberFriendBean> list1 = friendBeanList.stream().filter(o -> o.getFriendId() == null).collect(Collectors.toList());
            //主动参与用户里面的男性数量
            Long maxs = list1.stream().filter(o -> o.getGender() == 1).count();
            int womans = list1.size() - maxs.intValue();
            MemberRatioBean memberRatioBean1 = new MemberRatioBean();
            memberRatioBean1.setMaxRatio(df.format((float) maxs.intValue() / list1.size()));
            memberRatioBean1.setWomanRatio(df.format((float) womans / list1.size()));
            resultList.add(memberRatioBean1);

            //被邀请用户
            List<MemberFriendBean> list2 = friendBeanList.stream().filter(o -> o.getFriendId() != null).collect(Collectors.toList());
            //被邀请用户里面的男性数量
            Long maxs2 = list2.stream().filter(o -> o.getGender() == 1).count();
            int womans2 = list2.size() - maxs2.intValue();
            MemberRatioBean memberRatioBean2 = new MemberRatioBean();
            memberRatioBean2.setMaxRatio(df.format((float) maxs2.intValue() / list2.size()));
            memberRatioBean2.setWomanRatio(df.format((float) womans2 / list2.size()));
            resultList.add(memberRatioBean2);
            return resultList;
        }
        return resultList;
    }


    @Override
    public MemberTraderRonseespBean findMemberIdNumTodayTraderList(MemberAngParamBean memberAngParamBean) {
        MemberTraderRonseespBean memberTraderRonseespBean = new MemberTraderRonseespBean();
        //回租用户 并且有回租时长查询条件
        if (memberAngParamBean.getUserType() != null && memberAngParamBean.getUserType() == 2 &&
                memberAngParamBean.getTraderTypeHz() != null && memberAngParamBean.getTraderTypeHz() == 1) {
            List<String> memberIds = memberAnalyseMapper.queryMemberUserByLeasebackDay(memberAngParamBean.getLeasebackDay(), memberAngParamBean.getCharacter());
            if (!CollectionUtils.isEmpty(memberIds)){
                memberAngParamBean.setMemberIds(memberIds);
            }else {
                return memberTraderRonseespBean;
            }
        }
        List<MemberTraderBean> memberTraderBeanList = memberAnalyseMapper.queryMemberIdNumTodayTraderList(memberAngParamBean);
        if (!CollectionUtils.isEmpty(memberTraderBeanList)) {
            //todo  交易时段 24个点
            //1.先按照性别分组 男猪们
            List<MemberTraderBean> manList = memberTraderBeanList.stream().filter(o -> o.getGender() == 1).collect(Collectors.toList());
            //2.按照交易时间分组统计
            Map<String, List<MemberTraderBean>> manMaps = manList.stream().collect(Collectors.groupingBy(b -> b.getTraderDate()));
            //女猪们
            List<MemberTraderBean> woManList = memberTraderBeanList.stream().filter(o -> o.getGender() == 2).collect(Collectors.toList());
            Map<String, List<MemberTraderBean>> woManMaps = woManList.stream().collect(Collectors.groupingBy(b -> b.getTraderDate()));

            memberTraderRonseespBean.setManList(transFormResult(manMaps));
            memberTraderRonseespBean.setWoManList(transFormResult(woManMaps));
        }else {
            memberTraderRonseespBean.setManList(transFormResult(new HashMap<>()));
            memberTraderRonseespBean.setWoManList(transFormResult(new HashMap<>()));
        }
        return memberTraderRonseespBean;
    }

    /**
     * 月处理
     *
     * @param list
     * @return
     */
    public List<ActiveMemberBean> getActiveMemberList(List<ActiveMemberBean> list) {
        List<ActiveMemberBean> result = new ArrayList<>();
       /* //获取起始时间
        LocalDate startTime = LocalDate.parse(list.get(0).getDay());
        //获取结束时间
        LocalDate endTime = LocalDate.parse(list.get(list.size() -1).getDay());
        //开始月份
        long month = untilMonth(startTime,endTime) +1;
        if(startTime.getMonthValue() != endTime.getMonthValue()){
            month +=1;
        }*/
        SimpleDateFormat dateFormat = new SimpleDateFormat(NORMAL_MONTH_FORMAT);
        try {
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(dateFormat.parse(list.get(0).getDay()));

            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(dateFormat.parse(list.get(list.size() - 1).getDay()));
            for (; ; ) {
                ActiveMemberBean bean = new ActiveMemberBean();
                bean.setDay(dateFormat.format(startCalendar.getTime()));
                result.add(bean);
                if (StringUtils.equals(dateFormat.format(startCalendar.getTime()), dateFormat.format(endCalendar.getTime()))) {
                    break;
                }
                startCalendar.add(Calendar.MONTH, 1);
            }
            for (ActiveMemberBean resultBean : result) {
                int buyNumber = 0;
                int sellerNumber = 0;
                for (ActiveMemberBean bean : list) {
                    if (StringUtils.equals(resultBean.getDay(), dateFormat.format(dateFormat.parse(bean.getDay())))) {
                        buyNumber += bean.getBuyNumber();
                        sellerNumber += bean.getSellerNumber();
                    }
                }
                resultBean.setBuyNumber(buyNumber);
                resultBean.setSellerNumber(sellerNumber);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        /*for(int i=0;i<month;i++){
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM");
            String startTimeString = df.format(startTime);
            Integer buyNumber = 0;
            Integer sellerNumber = 0;
            List<ActiveMemberBean> list1 = list.stream().filter(o -> o.getDay().contains(startTimeString)).collect(Collectors.toList());
            ActiveMemberBean bean = new ActiveMemberBean();
            bean.setDay(startTimeString);
            for(ActiveMemberBean entity:list1){
                buyNumber += entity.getBuyNumber();
                sellerNumber += entity.getSellerNumber();
            }
            bean.setBuyNumber(buyNumber);
            bean.setSellerNumber(sellerNumber);
            result.add(bean);
            startTime = startTime.plusMonths(1);
        }*/
        return result;
    }

    /**
     * 计算日期{@code startDate}与{@code endDate}的间隔天数
     *
     * @param startDate
     * @param endDate
     * @return 间隔天数
     */
    public static long untilMonth(LocalDate startDate, LocalDate endDate) {
        return startDate.until(endDate, ChronoUnit.MONTHS);
    }

    /**
     * 交易时间段数据转换
     * @param paramsMap
     * @return
     */
    public List<Integer> transFormResult(Map<String,List<MemberTraderBean>> paramsMap){
        List<Integer> resultList = new ArrayList<>();
        for (int i = 0; i <= 23; i++) {
            if (i < 10) {
                if (paramsMap.get("0" + i) != null) {
                    List<MemberTraderBean> memberTraderBeanList = paramsMap.get("0" + i);
                    int traderNum = memberTraderBeanList.stream().collect(Collectors.summingInt(MemberTraderBean::getTraderNum));
                    resultList.add(traderNum);
                } else {
                    resultList.add(0);
                }
            } else {
                if (paramsMap.get(i + "") != null) {
                    List<MemberTraderBean> memberTraderBeanList = paramsMap.get(i + "");
                    int traderNum = memberTraderBeanList.stream().collect(Collectors.summingInt(MemberTraderBean::getTraderNum));
                    resultList.add(traderNum);
                } else {
                    resultList.add(0);
                }
            }
        }
        return resultList;
    }
    public static void main(String[] args) {
       /* List<BigDecimal> ageList = new ArrayList<>();
        BigDecimal dt1 = new BigDecimal(15);
        BigDecimal dt2 = new BigDecimal(18);
        BigDecimal dt3 = new BigDecimal(20);
        BigDecimal dt4 = new BigDecimal(28);
        ageList.add(dt1);
        ageList.add(dt2);
        ageList.add(dt3);
        ageList.add(dt4);
        BigDecimal dt5 = new BigDecimal(17);
        System.out.println(dt5.compareTo(BigDecimal.valueOf(18)));
        List<BigDecimal> list = ageList.stream().filter(o -> o.compareTo(BigDecimal.valueOf(0)) >0 && o.compareTo(BigDecimal.valueOf(18)) <0).collect(Collectors.toList());
        System.out.println(list);*/
       /* List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("6");
        list.add("7");
        list.add("8");
        list.add("9");
        list.add("10");
        list.add("11");
        list = list.stream().skip(5).collect(Collectors.toList());
        List<String> pagingData = list.stream().limit(5).collect(Collectors.toList());
        System.out.println(pagingData);*/
       /* DecimalFormat df=new DecimalFormat("##.##");
        double d=0.00d;
        String st=df.format(d);
        System.out.println(st);
        System.out.println();*/
      /* Double dt1 = 0.00d;
       Double dt2 = 0.00d;
       BigDecimal dt = new BigDecimal("0.00");
        System.out.println(dt.intValue());
        System.out.println(dt1/dt2);*/
       /* DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate startTime = LocalDate.parse("2018-04-24");
        LocalDate endTime = LocalDate.parse("2018-05-23");
        System.out.println(df.format(startTime));
        System.out.println(untilMonth(startTime,endTime));
        System.out.println(startTime.getMonthValue());
        System.out.println(endTime.getMonthValue());*/
        System.out.println(1 * 1.0 / 3);
    }
}
